﻿Public Class svcOvpnCntrl

    ' BITS Secure WLAN Service
    ' (c) 2012 chris burri @ Burri IT Systems

#Region "Declares"
    Private Event X As System.Net.NetworkInformation.NetworkAvailabilityChangedEventHandler
    Private WithEvents Manager As OpenVPNWinSvc.Library.OpenVPNTunMgr
    Private Suspended As Boolean = False
    Private SvcTitle As String = "OpenVPN Windows Service"
#End Region

#Region "Service Control"
    Private Sub Startup()
        ' create tunnel manager instance
        Try
            Manager = New OpenVPNWinSvc.Library.OpenVPNTunMgr
            ' start tunnels
            Manager.StartTunnels()
            ' collect garbage
            GC.Collect()
        Catch ex As Exception

            Trace.WriteLine("Service:Startup(): " & ex.Message)
        End Try
    End Sub

    Private Sub Shutdown()
        Try
            ' request 15000 milliseconds for shutdown
            MyBase.RequestAdditionalTime(15000)
        Catch ex As Exception
            ' ignore errors
        End Try
        ' stop all tunnels
        Manager.StopTunnels()
        ' collect garbage
        GC.Collect()
    End Sub
#End Region

#Region "Event Handlers"
    Protected Overrides Sub OnStart(ByVal args() As String)
        ' setup handler for NetworkAvailabilityChanged event
        AddHandler My.Computer.Network.NetworkAvailabilityChanged, AddressOf MyComputerNetwork_NetworkAvailabilityChanged
        ' write log
        Log(SvcTitle & " starting (requested)...", EventLogEntryType.Information)
        ' start all tunnels
        Startup()
    End Sub

    Protected Overrides Sub OnStop()
        ' remove handler for NetworkAvailabilityChanged event
        RemoveHandler My.Computer.Network.NetworkAvailabilityChanged, AddressOf MyComputerNetwork_NetworkAvailabilityChanged
        ' write log
        Log(SvcTitle & " stopping (requested)...", EventLogEntryType.Information)
        ' shutdown all tunnels
        Shutdown()
    End Sub

    Protected Overrides Sub OnShutdown()
        ' ### DEBUG: this event may or may not be raised. Nobody can give consistent details about it.
        Log(SvcTitle & " stopping (shutdown)...", EventLogEntryType.Information)
        ' according to some MS employee, we have to call the Stop() method ourselfes
        Me.Stop()
    End Sub

    Protected Overrides Function OnPowerEvent(powerStatus As System.ServiceProcess.PowerBroadcastStatus) As Boolean
        Select Case powerStatus
            Case ServiceProcess.PowerBroadcastStatus.BatteryLow
                ' ignore
            Case ServiceProcess.PowerBroadcastStatus.QuerySuspend
                ' acknowledge
                ' ## DEBUG: this event NEVER occurs ?!!
                Return True
            Case ServiceProcess.PowerBroadcastStatus.QuerySuspendFailed
                ' ignore
            Case ServiceProcess.PowerBroadcastStatus.ResumeAutomatic, _
                 ServiceProcess.PowerBroadcastStatus.ResumeCritical, _
                 ServiceProcess.PowerBroadcastStatus.ResumeSuspend
                ' trigger only if system was suspended
                If Suspended Then
                    ' system was suspended, resume now
                    Suspended = False
                    ' write log
                    Log(SvcTitle & " starting (resume)...", EventLogEntryType.Information)
                    ' start VPN tunnels
                    Startup()
                End If
            Case ServiceProcess.PowerBroadcastStatus.Suspend
                ' system suspended
                Suspended = True
                ' write log
                Log(SvcTitle & " stopping (suspend)...", EventLogEntryType.Information)
                ' stop VPN tunnels
                Shutdown()
        End Select
        Return MyBase.OnPowerEvent(powerStatus)
    End Function

    Public Sub MyComputerNetwork_NetworkAvailabilityChanged(ByVal sender As Object, ByVal e As Devices.NetworkAvailableEventArgs)
        Static NetWasAvailable As Boolean
        If Not e.IsNetworkAvailable = NetWasAvailable Then
            If e.IsNetworkAvailable Then
                ' network became available
                Log(SvcTitle & " starting (network available)...", EventLogEntryType.Information)
                Startup()
            Else
                ' network became unavailable
                Log(SvcTitle & " stopping (network unavailable)...", EventLogEntryType.Information)
                Shutdown()
            End If
        End If
    End Sub
#End Region

    Private Sub Log(Message As String, Eventtype As EventLogEntryType)
        OpenVPNWinSvc.Library.OpenVPNLogging.WLog(Message, Eventtype)
    End Sub
    Private Sub Dbg(Message As String)
        OpenVPNWinSvc.Library.OpenVPNLogging.WDbg(Message)
    End Sub




    Protected Overrides Sub Finalize()
        Manager = Nothing
        MyBase.Finalize()
    End Sub
End Class
